<template>
  <div class="equipment-attachment">
    <div class="header-wrapper">
      <div class="attachment-title">文档附件</div>
    </div>
    <div class="data-wrapper">
      <!-- 设备照片部分 -->
      <div class="attachment-section">
        <div class="section-header">
          <span class="section-title">设备照片</span>
          <el-button
            v-if="!props.isLook"
            type="primary"
            link
            class="section-btn"
            @click="handleUploadPhoto"
            :loading="uploadLoading"
            :disabled="uploadLoading"
          >
            上传设备照片
          </el-button>
        </div>
        <div class="photo-grid">
          <div
            v-for="(photo, index) in photoList"
            :key="photo.id || index"
            class="photo-item"
            @click="handlePreviewFile(photo, 'image')"
          >
            <img :src="photo.url" :alt="photo.name" class="photo-image" />
            <div class="photo-overlay">
              <el-icon class="preview-icon"><View /></el-icon>
            </div>
            <div v-if="!props.isLook" class="photo-actions">
              <el-button
                type="danger"
                size="small"
                circle
                @click.stop="deletePhoto(photo)"
              >
                <el-icon><Delete /></el-icon>
              </el-button>
            </div>
          </div>

          <!-- 空位占位符 -->
          <template v-if="!props.isLook">
            <div
              v-for="index in Math.max(0, 3 - photoList.length)"
              :key="`empty-${index}`"
              class="photo-item empty"
              @click="handleUploadPhoto"
            >
              <div class="empty-content">
                <el-icon class="empty-icon"><Plus /></el-icon>
                <span class="empty-text">添加照片</span>
              </div>
            </div>
          </template>
        </div>
      </div>

      <!-- 设备资料部分 -->
      <div class="attachment-section">
        <div class="section-header">
          <span class="section-title">设备资料</span>
          <el-button
            v-if="!props.isLook"
            type="primary"
            link
            class="section-btn"
            @click="handleUploadDocument"
            :loading="uploadLoading"
            :disabled="uploadLoading"
          >
            上传设备资料
          </el-button>
        </div>
        <div class="document-list">
          <div
            v-for="(doc, index) in documentList"
            :key="doc.id || index"
            class="document-item"
            @click="handlePreviewFile(doc, getFileType(doc.name))"
          >
            <div class="document-icon">
              <el-icon :size="24">
                <Document v-if="isPdf(doc.name)" />
                <Document v-else-if="isWord(doc.name)" />
                <Grid v-else-if="isExcel(doc.name)" />
                <VideoPlay v-else-if="isPpt(doc.name)" />
                <Document v-else />
              </el-icon>
            </div>
            <div class="document-info">
              <div class="document-name">{{ doc.name }}</div>
              <div class="document-size">{{ formatFileSize(doc.size) }}</div>
            </div>
            <div class="document-actions">
              <el-button
                type="primary"
                size="small"
                link
                @click.stop="handlePreviewFile(doc, getFileType(doc.name))"
              >
                预览
              </el-button>
              <el-button
                v-if="!props.isLook"
                type="danger"
                size="small"
                link
                @click.stop="deleteDocument(doc)"
              >
                删除
              </el-button>
            </div>
          </div>

          <!-- 空状态 -->
          <div v-if="documentList.length === 0" class="empty-documents">
            <el-icon class="empty-icon"><Document /></el-icon>
            <span class="empty-text">暂无设备资料</span>
          </div>
        </div>
      </div>

      <!-- 上传进度条 -->
      <div v-if="uploadLoading" class="upload-progress">
        <el-progress
          :percentage="uploadProgress"
          :show-text="true"
          status="success"
        />
        <div class="progress-text">正在上传文件...</div>
      </div>
    </div>

    <!-- 文件预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      :title="previewFile?.name"
      width="80%"
      :before-close="handleClosePreview"
      class="preview-dialog"
    >
      <Preview
        v-if="previewFile"
        :file-type="previewFileType"
        :file-url="previewFile.url"
        :file-name="previewFile.name"
        height="600px"
      />
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, defineProps, watch } from "vue";
import { ElMessage, ElMessageBox, ElDialog } from "element-plus";
import {
  View,
  Delete,
  Plus,
  Document,
  Grid,
  VideoPlay,
} from "@element-plus/icons-vue";
import Preview from "@/components/Doc/Preview.vue";
import { uploadFileAPI, deleteFileAPI } from "@/api/service/files";
import {
  updateDeviceFilesAPI,
  getEquipmentByIdAPI,
} from "@/api/service/equipmentManage";

// Props
interface Props {
  equipmentId: string;
  isLook?: boolean;
}

const props = defineProps<Props>();

// 响应式数据
const photoList = ref<FileItem[]>([]);
const documentList = ref<FileItem[]>([]);
const loading = ref(false);

// 文件上传相关
const uploadLoading = ref(false);
const uploadProgress = ref(0);

// 文件预览相关
const previewDialogVisible = ref(false);
const previewFile = ref<FileItem | null>(null);
const previewFileType = ref("");

// 文件类型定义
interface FileItem {
  id: string;
  name: string;
  url: string;
  size: number;
  type?: string;
}

// 加载设备文件
const loadEquipmentFiles = async () => {
  if (!props.equipmentId) return;

  try {
    loading.value = true;
    const response = await getEquipmentByIdAPI(props.equipmentId);
    const equipmentData = response.data || response;

    // 获取照片文件详情
    equipmentData.photoList?.forEach((item: any) => {
      item.url = item.accessUrl;
    });
    photoList.value = equipmentData.photoList || [];

    // 获取文档文件详情
    equipmentData.documentList?.forEach((item: any) => {
      item.url = item.accessUrl;
    });
    documentList.value = equipmentData.documentList || [];
  } catch (error) {
    console.error("加载设备文件失败:", error);
    ElMessage.error("加载设备文件失败");
  } finally {
    loading.value = false;
  }
};

// 监听设备ID变化，重新加载数据
watch(
  () => props.equipmentId,
  (newId) => {
    if (newId) {
      loadEquipmentFiles();
    }
  },
  { immediate: true }
);

// 文件类型判断
const isPdf = (fileName: string) => /\.pdf$/i.test(fileName);
const isWord = (fileName: string) => /\.(doc|docx)$/i.test(fileName);
const isExcel = (fileName: string) => /\.(xls|xlsx)$/i.test(fileName);
const isPpt = (fileName: string) => /\.(ppt|pptx)$/i.test(fileName);

const getFileType = (fileName: string) => {
  if (isPdf(fileName)) return "pdf";
  if (isWord(fileName)) return "doc";
  if (isExcel(fileName)) return "excel";
  if (isPpt(fileName)) return "ppt";
  return "document";
};

// 文件大小格式化
const formatFileSize = (bytes: number) => {
  if (bytes === 0) return "0 B";
  const k = 1024;
  const sizes = ["B", "KB", "MB", "GB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + " " + sizes[i];
};

// 创建文件输入元素
const createFileInput = (
  accept: string,
  multiple = false
): HTMLInputElement => {
  const input = document.createElement("input");
  input.type = "file";
  input.accept = accept;
  input.multiple = multiple;
  input.style.display = "none";
  document.body.appendChild(input);
  return input;
};

// 上传照片
const handleUploadPhoto = () => {
  const input = createFileInput("image/*", true);

  input.onchange = async (event) => {
    const files = (event.target as HTMLInputElement).files;
    if (!files || files.length === 0) {
      document.body.removeChild(input);
      return;
    }

    try {
      uploadLoading.value = true;
      const uploadedFiles: FileItem[] = [];

      for (let i = 0; i < files.length; i++) {
        const file = files[i];

        // 检查文件大小（限制为100MB）
        if (file.size > 100 * 1024 * 1024) {
          ElMessage.error(`${file.name} 文件大小超过100MB限制`);
          continue;
        }

        // 上传文件
        const uploadResult = await uploadFileAPI(file, (progress) => {
          uploadProgress.value = progress;
        });

        const uploadData = uploadResult.data || uploadResult;
        if (uploadData) {
          uploadedFiles.push({
            id: uploadData.id,
            name: file.name,
            url: uploadData.accessUrl,
            size: file.size,
            type: "image",
          });
        }
      }

      if (uploadedFiles.length > 0) {
        // 更新设备文件绑定关系
        const currentPhotoIds = photoList.value.map((photo) => photo.id);
        const newPhotoIds = [
          ...currentPhotoIds,
          ...uploadedFiles.map((file) => file.id),
        ];

        await updateDeviceFilesAPI({
          deviceId: props.equipmentId,
          photoIds: newPhotoIds,
          documentIds: documentList.value.map((doc) => doc.id),
        });

        // 更新本地数据
        photoList.value.push(...uploadedFiles);
        ElMessage.success(`成功上传 ${uploadedFiles.length} 张照片`);
      }
    } catch (error: any) {
      console.error("上传照片失败:", error.message);
      ElMessage.error(error.message);
    } finally {
      uploadLoading.value = false;
      uploadProgress.value = 0;
      document.body.removeChild(input);
    }
  };

  input.click();
};

// 上传文档
const handleUploadDocument = () => {
  const input = createFileInput(
    ".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.txt",
    true
  );

  input.onchange = async (event) => {
    const files = (event.target as HTMLInputElement).files;
    if (!files || files.length === 0) {
      document.body.removeChild(input);
      return;
    }

    try {
      uploadLoading.value = true;
      const uploadedFiles: FileItem[] = [];

      for (let i = 0; i < files.length; i++) {
        const file = files[i];

        // 检查文件大小（限制为500MB）
        if (file.size > 500 * 1024 * 1024) {
          ElMessage.error(`${file.name} 文件大小超过500MB限制`);
          continue;
        }

        // 上传文件
        const uploadResult = await uploadFileAPI(file, (progress) => {
          uploadProgress.value = progress;
        });

        const uploadData = uploadResult.data || uploadResult;
        if (uploadData) {
          uploadedFiles.push({
            id: uploadData.id,
            name: file.name,
            url: uploadData.accessUrl,
            size: file.size,
            type: "document",
          });
        }
      }

      if (uploadedFiles.length > 0) {
        // 更新设备文件绑定关系
        const currentDocumentIds = documentList.value.map((doc) => doc.id);
        const newDocumentIds = [
          ...currentDocumentIds,
          ...uploadedFiles.map((file) => file.id),
        ];

        await updateDeviceFilesAPI({
          deviceId: props.equipmentId,
          photoIds: photoList.value.map((photo) => photo.id),
          documentIds: newDocumentIds,
        });

        // 更新本地数据
        documentList.value.push(...uploadedFiles);
        ElMessage.success(`成功上传 ${uploadedFiles.length} 个文档`);
      }
    } catch (error) {
      console.error("上传文档失败:", error);
      ElMessage.error("上传文档失败");
    } finally {
      uploadLoading.value = false;
      uploadProgress.value = 0;
      document.body.removeChild(input);
    }
  };

  input.click();
};

// 预览文件
const handlePreviewFile = (file: FileItem, fileType: string) => {
  try {
    previewFile.value = file;
    previewFileType.value = fileType;
    previewDialogVisible.value = true;
  } catch (error) {
    console.error("预览文件失败:", error);
    ElMessage.error("预览文件失败");
  }
};

// 关闭预览对话框
const handleClosePreview = () => {
  previewDialogVisible.value = false;
  previewFile.value = null;
  previewFileType.value = "";
};

// 删除照片
const deletePhoto = async (photo: FileItem) => {
  try {
    await ElMessageBox.confirm("确定要删除这张照片吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    // 删除文件
    await deleteFileAPI(photo.id);

    // 更新设备文件绑定关系
    const updatedPhotoIds = photoList.value
      .filter((item) => item.id !== photo.id)
      .map((item) => item.id);

    await updateDeviceFilesAPI({
      deviceId: props.equipmentId,
      photoIds: updatedPhotoIds,
      documentIds: documentList.value.map((doc) => doc.id),
    });

    // 更新本地数据
    const index = photoList.value.findIndex((item) => item.id === photo.id);
    if (index > -1) {
      photoList.value.splice(index, 1);
      ElMessage.success("删除成功");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除照片失败:", error);
      ElMessage.error("删除失败");
    }
  }
};

// 删除文档
const deleteDocument = async (doc: FileItem) => {
  try {
    await ElMessageBox.confirm("确定要删除这个文档吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    // 删除文件
    await deleteFileAPI(doc.id);

    // 更新设备文件绑定关系
    const updatedDocumentIds = documentList.value
      .filter((item) => item.id !== doc.id)
      .map((item) => item.id);

    await updateDeviceFilesAPI({
      deviceId: props.equipmentId,
      photoIds: photoList.value.map((photo) => photo.id),
      documentIds: updatedDocumentIds,
    });

    // 更新本地数据
    const index = documentList.value.findIndex((item) => item.id === doc.id);
    if (index > -1) {
      documentList.value.splice(index, 1);
      ElMessage.success("删除成功");
    }
  } catch (error) {
    if (error !== "cancel") {
      console.error("删除文档失败:", error);
      ElMessage.error("删除失败");
    }
  }
};
</script>

<style scoped lang="scss">
.equipment-attachment {
  .section-btn {
    padding: 0.2rem 1rem;
    color: $text-color-regular;
    font-size: $font-size-base-btn-text;
    cursor: pointer;
    background: $bg-td-2-color;
    border-radius: 0.5rem;
  }
  .header-wrapper {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 1.5rem;
    background-color: #eee;
    border-bottom: 1px solid #dddddd;
    .attachment-title {
      font-size: $font-size-page-menu;
      font-weight: 600;
      color: #2f2f2f;
      padding-left: 12px;
      border-left: 4px solid #667eea;
    }
  }

  .data-wrapper {
    padding: 1.5rem;
    background-color: #fff;
  }

  .upload-progress {
    margin-bottom: 24px;
    padding: 16px;
    background: #f0f9ff;
    border-radius: 8px;
    border: 1px solid #b3d8ff;

    .progress-text {
      margin-top: 8px;
      text-align: center;
      color: #409eff;
      font-size: 14px;
    }
  }

  .attachment-section {
    margin-bottom: 32px;

    &:last-child {
      margin-bottom: 0;
    }

    .section-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      .section-title {
        font-size: 16px;
        font-weight: 500;
        color: #303133;
      }
    }
  }

  // 照片网格
  .photo-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 16px;
    max-width: 100%;

    .photo-item {
      position: relative;
      width: 100%;
      height: 150px;
      border: 2px dashed #d9d9d9;
      border-radius: 8px;
      overflow: hidden;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        border-color: #409eff;

        .photo-overlay {
          opacity: 1;
        }

        .photo-actions {
          opacity: 1;
        }
      }

      &.empty {
        display: flex;
        align-items: center;
        justify-content: center;
        background: #fafafa;

        .empty-content {
          display: flex;
          flex-direction: column;
          align-items: center;
          color: #909399;

          .empty-icon {
            font-size: 32px;
            margin-bottom: 8px;
          }

          .empty-text {
            font-size: 14px;
          }
        }

        &:hover {
          background: #f0f9ff;
          border-color: #409eff;
          color: #409eff;
        }
      }

      .photo-image {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }

      .photo-overlay {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background: rgba(0, 0, 0, 0.5);
        display: flex;
        align-items: center;
        justify-content: center;
        opacity: 0;
        transition: opacity 0.3s;

        .preview-icon {
          color: #fff;
          font-size: 24px;
        }
      }

      .photo-actions {
        position: absolute;
        top: 8px;
        right: 8px;
        opacity: 0;
        transition: opacity 0.3s;
      }
    }
  }

  // 文档列表
  .document-list {
    .document-item {
      display: flex;
      align-items: center;
      padding: 16px;
      border: 1px solid #e4e7ed;
      border-radius: 8px;
      margin-bottom: 12px;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        border-color: #409eff;
        background: #f0f9ff;
      }

      &:last-child {
        margin-bottom: 0;
      }

      .document-icon {
        margin-right: 16px;
        color: #409eff;
      }

      .document-info {
        flex: 1;

        .document-name {
          font-size: 14px;
          color: #303133;
          margin-bottom: 4px;
        }

        .document-size {
          font-size: 12px;
          color: #909399;
        }
      }

      .document-actions {
        display: flex;
        gap: 8px;
        .el-button {
          padding: 0.2rem 1rem;
          color: $text-color-regular;
          font-size: $font-size-base-btn-text;
          cursor: pointer;
        }
      }
    }

    .empty-documents {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      padding: 48px 24px;
      color: #909399;

      .empty-icon {
        font-size: 48px;
        margin-bottom: 16px;
      }

      .empty-text {
        font-size: 14px;
      }
    }
  }

  // 预览对话框样式
  .preview-dialog {
    :deep(.el-dialog) {
      margin-top: 5vh;
    }

    :deep(.el-dialog__body) {
      padding: 0;
      max-height: 70vh;
      overflow: hidden;
    }
  }
}
</style>
